package flex.cc.drive.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.common.utils.DateUtil;
import flex.cc.common.utils.HttpClientUtil;
import flex.cc.common.utils.OrderNoGenerateUtil;
import flex.cc.drive.dao.DriverInterfaceLogDao;
import flex.cc.drive.dao.OrderDriverDao;
import flex.cc.drive.dto.DriverInterfaceLogEntity;
import flex.cc.drive.dto.DriverRemarkEntity;
import flex.cc.drive.dto.OrderDriveVo;
import flex.cc.drive.dto.OrderDriverEntity;
import flex.cc.drive.service.DriverRemarkService;
import flex.cc.drive.service.OrderDriverService;
import flex.cc.drive.util.DriveDESUtil;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.util.APIConfigUtil;
import flex.cc.util.SpecialRuleUtil;

/**
*
* @author R
* 2022年01月14日 13:35:01
* @desc 代驾单实现层
*/
@Service("orderDriverService")
@Transactional(rollbackFor = Exception.class)
public class OrderDriverServiceImpl implements OrderDriverService {
    private static final Logger logger = LoggerFactory.getLogger(OrderDriverServiceImpl.class);
    
//    @Value("${api.config.createBespeakOrderUrl}")
//    private String createBespeakOrderUrl;
//    @Value("${api.config.key}")
//    private String key;
//    @Value("${redeemcode.source}")
//    private String source;
    @Autowired
    private OrderDriverDao orderDriverDao;
    @Autowired
    private DriverInterfaceLogDao driverInterfaceLogDao;
    @Autowired
    private DriverRemarkService remarkService;
    @Autowired
    private StoreCouponDao storeCouponDao;
    @Autowired
    private OrderNoGenerateUtil orderNoGenerateUtil;
    @Autowired
	private APIConfigUtil apiConfigUtil;
    @Autowired
	private SpecialRuleUtil specialRuleUtil;
    
	@Override
	public JSONObject createOrUpdateBespeakOrder(Map<String, Object> requestBodyMap) {
		JSONObject jsonResult = new JSONObject();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> requestMap = new HashMap<String, Object>();
		try {
			//控制该接口是新增预约还是修改预约接口
			String requestType = (String) requestBodyMap.get("requestType");
			dataMap.put("requestType", requestType);			
			//车牌号
			String carNumber = (String) requestBodyMap.get("carNo");
			if(PublicUtil.isEmpty(carNumber)) {
	    		logger.error("车牌号不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "车牌号不能为空");
	            return jsonResult;
			}
			//归属卡券码
			String couponNum = (String) requestBodyMap.get("couponNum");
			StoreCouponEntity storeCouponEntity = storeCouponDao.queryByCouponNum(couponNum);
			dataMap.put("orderId", couponNum);
	        /**
	         * 根据提交的卡券以及车牌号获取对应服务项目的特殊规则 判断是否符合规则
	         */
	        //TODO 预约开关配置,requestType：CREATE-新增预约 
	        if ("CREATE".equals(requestType)) {
	        	boolean ruleResult = specialRuleUtil.judgeSpecialRule(couponNum,carNumber);
	        	if(!ruleResult){
	        		jsonResult.put("resultCode", "01");
	        		jsonResult.put("resultDesc", "本月使用次数已达到上限，详情请查看\"使用规则\"说明");
		            return jsonResult;
	        	}
	        }
			
			//用户名
			String userName = (String) requestBodyMap.get("contacts");
			if(PublicUtil.isEmpty(userName)) {
	    		logger.error("用户名不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "用户名不能为空");
	            return jsonResult;
			}
			dataMap.put("userName", userName);
			//联系电话
			String telphone = (String) requestBodyMap.get("tel");
			if(PublicUtil.isEmpty(telphone)) {
	    		logger.error("联系电话不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "联系电话不能为空");
	            return jsonResult;
			}
			dataMap.put("telphone", telphone);

			dataMap.put("telphone", telphone);
			//预约时间
			String bespeakTime = (String) requestBodyMap.get("appointTime");
			if(PublicUtil.isEmpty(bespeakTime)) {
	    		logger.error("预约时间不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "预约时间不能为空");
	            return jsonResult;
			}
			dataMap.put("bespeakTime", bespeakTime);
			//起始地经度
			String longitude = (String) requestBodyMap.get("longitude");
			if(PublicUtil.isEmpty(longitude)) {
	    		logger.error("起始地经度不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "出发地经度不能为空");
	            return jsonResult;
			}	
			dataMap.put("longitude", longitude);
			//起始地纬度
			String latitude = (String) requestBodyMap.get("latitude");
			if(PublicUtil.isEmpty(latitude)) {
	    		logger.error("起始地纬度不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "出发地纬度不能为空");
	            return jsonResult;
			}		
			dataMap.put("latitude", latitude);
			//目的地经度
			String deLongitude = (String) requestBodyMap.get("deLongitude");
			if(PublicUtil.isEmpty(deLongitude)) {
	    		logger.error("目的地经度不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "目的地经度不能为空");
	            return jsonResult;
			}
			dataMap.put("deLongitude", deLongitude);
			//目的地纬度
			String deLatitude = (String) requestBodyMap.get("deLatitude");
			if(PublicUtil.isEmpty(deLatitude)) {
	    		logger.error("目的地纬度不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "目的地纬度不能为空");
	            return jsonResult;
			}		
			dataMap.put("deLatitude", deLatitude);
			//出发地省
			String departureProvince = (String) requestBodyMap.get("departureProvince");
			//出发地市
			String departureCity = (String) requestBodyMap.get("departureCity");
			dataMap.put("city", departureCity);
			//出发地区
			String departureArea = (String) requestBodyMap.get("departureArea");
			//目的地省
			String destinationProvince = (String) requestBodyMap.get("destinationProvince");
			//目的地市
			String destinationCity = (String) requestBodyMap.get("destinationCity");
			//目的地区
			String destinationArea = (String) requestBodyMap.get("destinationArea");
			

			//归属服务包
			String packageCode = (String) requestBodyMap.get("packageCode");
			
			//系统默认酒后代驾  需要传递出发地详细地址和目的地详细地址
			//出发地
			String startAddress = (String) requestBodyMap.get("departure");
			if(PublicUtil.isEmpty(startAddress)) {
	    		logger.error("上车地址不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "上车地址不能为空");
	            return jsonResult;
			}
			dataMap.put("startAddress", startAddress);
			//目的地
			String endAddress = (String) requestBodyMap.get("destination");
			if(PublicUtil.isEmpty(endAddress)) {
	    		logger.error("下车地址不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "下车地址不能为空");
	            return jsonResult;
			}
			dataMap.put("endAddress", endAddress);
			

			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("couponNum", couponNum);
			StoreCouponEntity couponEntity = storeCouponDao.getOneByParams(params);
			String provider = couponEntity.getServer();
			
			String source = apiConfigUtil.getApiConfig(provider, "disponse_code");
			dataMap.put("source", source);
			

			logger.info(new Date() + "==" + dataMap.toString());
			//判断新增预约接口时 是更新服务单还是新增服务单
			boolean flag = false;
			OrderDriverEntity orderDriverEntity = null;
			//服务单号
			String orderNo = "";
			//服务单初始化状态  防止已派单或者预约成功 再次预约 下游会返回失败 再次更新服务单状态
			String initStatus = "";
			if(requestType.equals("CREATE")){//预约新增接口
				//现根据卡券编码 查询是否存在服务单
				//卡券取消可用后 再次进行预约 依然对该条数据进行处理
				orderDriverEntity = orderDriverDao.findByOrderId(couponNum);
				flag = orderDriverEntity==null?true:false;
				initStatus = orderDriverEntity==null?null:orderDriverEntity.getStatus();
				if(PublicUtil.isNotEmpty(initStatus)&&initStatus.equals("02")) {
		    		logger.error("服务单已派单，无需再次预约");
		    		jsonResult.put("resultCode", "01");
		    		jsonResult.put("resultDesc", "服务单已派单，无法再次预约");
		            return jsonResult;
				}		
				if(PublicUtil.isNotEmpty(initStatus)&&initStatus.equals("03")) {
		    		logger.error("服务单指派司机已到达，无需再次预约");
		    		jsonResult.put("resultCode", "01");
		    		jsonResult.put("resultDesc", "服务单指派司机已到达，无法再次预约");
		            return jsonResult;
				}
				if(PublicUtil.isNotEmpty(initStatus)&&initStatus.equals("04")) {
		    		logger.error("服务单服务已完成，无需再次预约");
		    		jsonResult.put("resultCode", "01");
		    		jsonResult.put("resultDesc", "服务单服务已完成，无法再次预约");
		            return jsonResult;
				}
				if(PublicUtil.isNotEmpty(initStatus)&&initStatus.equals("06")) {
		    		logger.error("服务单已核销取消，无需再次预约");
		    		jsonResult.put("resultCode", "01");
		    		jsonResult.put("resultDesc", "服务单已核销取消，无法再次预约");
		            return jsonResult;
				}
				
				if(flag){//新增预约单
					orderDriverEntity = new OrderDriverEntity();
					orderNo = orderNoGenerateUtil.getDriverOrderNo("00");
					//预约编号
					orderDriverEntity.setOrderNo(orderNo);
					orderDriverEntity.setOrderId(couponNum);
					orderDriverEntity.setPackageCode(packageCode);
					orderDriverEntity.setActivityId(storeCouponEntity.getActivityId());
				}else{//更新预约单
					orderNo = orderDriverEntity.getOrderNo();
				}
				//联系人
				orderDriverEntity.setContacts(userName);
				//联系电话
				orderDriverEntity.setTel(telphone);
				//车牌号
				orderDriverEntity.setCarNo(carNumber);
				//预约时间
				orderDriverEntity.setAppointTime(DateUtil.parseStringToDate(bespeakTime, "yyyy-MM-dd HH:mm:ss"));
				//出发地
				orderDriverEntity.setDeparture(startAddress);
				//目的地
				orderDriverEntity.setDestination(endAddress);
				//出发地省
				orderDriverEntity.setDepartureProvince(departureProvince);
				//出发地市
				orderDriverEntity.setDepartureCity(departureCity);
				//出发地区
				orderDriverEntity.setDepartureArea(departureArea);
				//目的地省
				orderDriverEntity.setDestinationProvince(destinationProvince);
				//目的地市
				orderDriverEntity.setDestinationCity(destinationCity);
				//目的地区
				orderDriverEntity.setDestinationArea(destinationArea);
				
				orderDriverEntity.setLongitude(longitude);
				orderDriverEntity.setLatitude(latitude);
				orderDriverEntity.setDeLongitude(deLongitude);
				orderDriverEntity.setDeLatitude(deLatitude);
				orderDriverEntity.setCancelFlag("0");
				
			}else{
				orderDriverEntity = orderDriverDao.findByOrderId(couponNum);
				orderNo = orderDriverEntity.getOrderNo();
				//联系人
				orderDriverEntity.setContacts(userName);
				//联系电话
				orderDriverEntity.setTel(telphone);
				//车牌号
				orderDriverEntity.setCarNo(carNumber);
				//预约时间
				orderDriverEntity.setAppointTime(DateUtil.parseStringToDate(bespeakTime, "yyyy-MM-dd HH:mm:ss"));
				//出发地
				orderDriverEntity.setDeparture(startAddress);
				//目的地
				orderDriverEntity.setDestination(endAddress);
				//出发地省
				orderDriverEntity.setDepartureProvince(departureProvince);
				//出发地市
				orderDriverEntity.setDepartureCity(departureCity);
				//出发地区
				orderDriverEntity.setDepartureArea(departureArea);
				//目的地省
				orderDriverEntity.setDestinationProvince(destinationProvince);
				//目的地市
				orderDriverEntity.setDestinationCity(destinationCity);
				//目的地区
				orderDriverEntity.setDestinationArea(destinationArea);
				
				orderDriverEntity.setLongitude(longitude);
				orderDriverEntity.setLatitude(latitude);
				orderDriverEntity.setDeLongitude(deLongitude);
				orderDriverEntity.setDeLatitude(deLatitude);
				orderDriverEntity.setCancelFlag("0");
			}

			JSONObject dateJsonObj=new JSONObject(dataMap);
			String key = apiConfigUtil.getApiConfig(provider, "drive_decode");
			String key3Des = apiConfigUtil.getApiConfig(provider, "store_key3Des");
			String encryptDateStr = DriveDESUtil.driverEncrypt(dateJsonObj.toString(), key,key3Des);
			requestMap.put("source", source);
			requestMap.put("data", encryptDateStr);
			JSONObject requestJsonObj=new JSONObject(requestMap);

			Date requestDate = new Date();
	        // 调用预约代驾单下单接口
			String createBespeakOrderUrl = apiConfigUtil.getApiConfig(provider, "drive_create");
			
			logger.info("预约代驾单下单接口接口url ==" + createBespeakOrderUrl);
			logger.info("预约代驾单下单接口接口请求报文 ==" + requestJsonObj.toString());
			
	    	String packageResult = HttpClientUtil.sendHttpPost(createBespeakOrderUrl, requestJsonObj.toString(), new HashMap<String, String>(){{
	            put("Content-Type", "application/json;charset=UTF-8");
	        }});
	    	Date responseDate = new Date();
	    	JSONObject resultObject = JSONObject.parseObject(packageResult);
	    	Map<String, Object> responseBodyMap = resultObject.toJavaObject(Map.class);
	    	//响应码
	    	String resultCode = (String) responseBodyMap.get("resultCode");
	    	//代驾单状态
	    	String status = "";
	    	if(resultCode.equals("success")){
	    		status = "01";
	    	}else{
	    		status = "00";
	    	}

	    	if(requestType.equals("CREATE")){
	    		if(flag){
	    			orderDriverEntity.setStatus(status);
	    	    	orderDriverEntity.setIsDelete(0);
	    	    	orderDriverEntity.setCreateTime(new Date());
	    	    	orderDriverEntity.setCreater("system");
	    	    	orderDriverEntity.setUpdateTime(new Date());
	    	    	orderDriverEntity.setUpdater("system");
	    	    	orderDriverDao.insert(orderDriverEntity);
	    		}else{
	    			if(initStatus.equals("00")||initStatus.equals("05")){//只有预约失败或者预约取消 才有可能再次预约
		    			orderDriverEntity.setStatus(status);
		    			orderDriverEntity.setUpdateTime(new Date());
		    	    	orderDriverEntity.setUpdater("system");
		    	    	orderDriverDao.updateByEntity(orderDriverEntity);
	    			}
	    		}
	    	}else{
	    		if(resultCode.equals("success")){
	    			orderDriverEntity.setStatus(status);
	    			orderDriverEntity.setCreateTime(new Date());
	    	    	orderDriverEntity.setCreater("system");
	    	    	orderDriverEntity.setUpdateTime(new Date());
	    	    	orderDriverEntity.setUpdater("system");
	    	    	orderDriverDao.updateByEntity(orderDriverEntity);
	    		}
	    	}
	    	String logDataId = UUID.randomUUID().toString().replace("-", "");
	    	DriverInterfaceLogEntity driverInterfaceLogEntity = new DriverInterfaceLogEntity();
	    	driverInterfaceLogEntity.setDataId(logDataId);
	    	driverInterfaceLogEntity.setOrderNo(orderNo);
	    	driverInterfaceLogEntity.setOrderId(couponNum);
	    	driverInterfaceLogEntity.setInterfaceName(requestType.equals("CREATE")?"预约新增接口":"预约修改接口");
	    	driverInterfaceLogEntity.setRequestTime(requestDate);
	    	driverInterfaceLogEntity.setRequestBody(requestJsonObj.toString());
	    	driverInterfaceLogEntity.setResponseBody(resultObject.toString());
	    	driverInterfaceLogEntity.setResponseTime(responseDate);
	    	driverInterfaceLogEntity.setCreateTime(new Date());
	    	driverInterfaceLogDao.insert(driverInterfaceLogEntity);
	    	
	    	String remarkDataId = UUID.randomUUID().toString().replace("-", "");
	    	DriverRemarkEntity driverRemarkEntity = new DriverRemarkEntity();
	    	driverRemarkEntity.setDataId(remarkDataId);
	    	driverRemarkEntity.setOrderNo(orderNo);
	    	driverRemarkEntity.setOrderId(couponNum);
	    	driverRemarkEntity.setStatus(resultCode.equals("SUCCESS")?"0":"1");
	    	driverRemarkEntity.setLink(requestType.equals("CREATE")?"预约新增":"预约修改");
	    	String type = requestType.equals("CREATE")?"预约新增":"预约修改";
	    	driverRemarkEntity.setRemark(status.equals("01")?type+"成功":type+"失败");
	    	driverRemarkEntity.setCreateTime(new Date());
	    	driverRemarkEntity.setCreator("system");
	    	driverRemarkEntity.setUpdateTime(new Date());
	    	driverRemarkEntity.setUpdater("system");
	    	driverRemarkEntity.setIsDelete(0);
	    	remarkService.insert(driverRemarkEntity);
	    	
	    	return resultObject;
		} catch (Exception e) {
			logger.info("请求代驾类预约新增/修改接口异常"+e.getMessage());
			jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "请求代驾类预约新增/修改接口异常");
            return jsonResult;
		}
	}

	/**
	 * @param params 查询参数
	 * @return
	 * @description 代驾服务进展信息
	 * @author wkangle
	 * @time 2022/01/19 0019 9:30
	 * @exception/throws
	 */
	@Override
	public OrderDriveVo drivingProgress(Map<String, Object> params) {
		System.out.println(new Date() + ": =====drivingProgress====== " + params);
		//logger.info(new Date() + ": =====drivingProgress====== " + params);
		// 预约代驾服务单信息
		Map<String, Object> orderDriverParams = new HashMap<>();
		orderDriverParams.put("couponNum", params.get("couponNum"));
		orderDriverParams.put("packageCode", params.get("packageCode"));
		orderDriverParams.put("carNo", params.get("carNo"));
		//orderDriverParams.put("status", "01"); // 预约成功
		return orderDriverDao.getOneByParams(orderDriverParams);

		//// 卡券信息
		//Map<String, Object> couponParams = new HashMap<>();
		//couponParams.put("id", params.get("id"));
		//StoreCouponEntity storeCouponEntity = storeCouponDao.getOneByParams(couponParams);
		//bookingInfoVo.setStoreCouponEntity(storeCouponEntity);
		//// 预约信息关联的门店信息
		//Map<String, Object> storeInfoParams = new HashMap<>();
		//System.out.println(bookingInfoVo.getStoreInfoId());
		//storeInfoParams.put("id", bookingInfoVo.getStoreInfoId());
		//StoreInfoEntity storeInfoEntity = storeInfoDao.getOneByParams(storeInfoParams);
		//bookingInfoVo.setStoreInfoEntity(storeInfoEntity);
		//
		//bookingInfoVo.setOptionType("1"); // 1-show
	}


}
